package src.com.atguigu04.set;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * ClassName: TreeSetTest
 * Description:
 *  TreeSet==>可以按照添加的元素的指定的属性的大小顺序进行遍历。
 *  有自然排序与定制排序
 * @Author liu
 * @Create 2025/4/2 21:32
 * @Version 1.0
 */
public class TreeSetTest {
    /*
    自然排序==>大到小
     */
    @Test
    public void test1(){
        TreeSet set = new TreeSet();

        set.add("AA");
        set.add("DD");
        set.add("CC");
        set.add("SS");
        set.add("BB");
        set.add("EE");
        set.add("RR");

        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());

        }
    }

    /**
     * 类的自然排序==>不用equals()与 hashCode()方法，但无法自然排序，要定制排序
     */
    @Test
    public void test2(){
      TreeSet set = new TreeSet();

        User u1 = new User("Tom",23);
        User u2 = new User("Jerry",43);
        User u3 = new User("Rose",13);
        User u4 = new User("Jack",23);
        User u5 = new User("Tony",33);

        set.add(u1);
        set.add(u2);
        set.add(u3);
        set.add(u4);
        set.add(u5);

        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }


    /*
     * 定制排序
     * */
    @Test
    public void test3(){
        Comparator comparator = new Comparator() {
            /*
             * 按照姓名从小到大排列，如果姓名相同，继续比较age，按照从大到小排列
             * */
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User){
                    User u1 = (User)o1;
                    User u2 = (User)o2;

                    int value = u1.getName().compareTo(u2.getName());
                    if(value != 0){
                        return value;
                    }
                    return -(u1.getYear() - u2.getYear());
                }
                throw new RuntimeException("类型不匹配");
            }
        };
        TreeSet set = new TreeSet(comparator);

        User u1 = new User("Tom",23);
        User u2 = new User("Jerry",43);
        User u3 = new User("Rose",13);
        User u4 = new User("Jack",23);
        User u5 = new User("Tony",33);

        set.add(u1);
        set.add(u2);
        set.add(u3);
        set.add(u4);
        set.add(u5);

        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}
